using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace PSE.Hosting.Management.Windows
{
    public partial class AddAssemblyForm : Form
    {
        private string _serverName;
        private string _packageName;
        private string[] _files;
        private List<string> _errors = new List<string>();

        public AddAssemblyForm(string serverName, string packageName)
        {
            InitializeComponent();
            _serverName = serverName;
            _packageName = packageName;
        }

        private void cmdOpenAssembly_Click(object sender, EventArgs e)
        {
            OpenAssemblyFileDialog.ShowDialog(this);
        }

        private void OpenAssemblyFileDialog_FileOk(object sender, CancelEventArgs e)
        {
            _files = OpenAssemblyFileDialog.FileNames;
            
            txtAssemblyFileName.Text = String.Join(",", _files);
        }

        private void cmdOk_Click(object sender, EventArgs e)
        {
            if (_files == null)
            {
                MessageBox.Show("You must select at least a single file to be added.", "Select File", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }


            _errors.Clear();
            
            for (int i = 0; i < _files.Length; i++)
            {
                this.AddAssembly(_files[i]);
            }

            if (_errors.Count > 0)
            {
                string message = String.Empty;
                
                foreach (string error in _errors)
                {
                    message += error + System.Environment.NewLine;
                }

                MessageBox.Show(message);
            }

            this.DialogResult = DialogResult.OK;

            this.Close();
        }

        private void AddAssembly(string fileName)
        {
            // Call the proxy to install the assembly.
            try
            {
                Business.AddAssembly(_serverName, _packageName, fileName);
                Business.StartAssembly(_serverName, _packageName, Path.GetFileName(fileName));
            }
            catch (Exception ex)
            {
                _errors.Add(ex.Message);
            }
            
        }

        private void cmdCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void AddAssemblyForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
                this.Close();
        }
    }
}